import pymysql


# 创建一个类
class UNTIL:
    # 创建类属性
    __conn = None
    __cursor = None

    # 创建链接数据库的类
    @classmethod
    def get_conn(cls):
        if cls.__conn == None:
            cls.__conn = pymysql.connect(host="127.0.0.1",
                                         port=3306,
                                         user="root",
                                         password="root",
                                         database="books",
                                         charset="utf8")
        return cls.__conn
        # 创建游标cursor

    @classmethod
    def get__cursor(cls):
        cls.__cursor = UNTIL.get_conn().cursor()
        return cls.__cursor

    # 书写sql语句并执行
    @classmethod
    def exe_sql(cls, sql):
        cursor = cls.get__cursor()
        try:
            if sql.split()[0].lower() == "select":
                cursor.execute(sql)
                return cursor.fetchall()
            else:
                cursor.execute()
                cls.__conn.commit
                return cursor.rowcount
        except Exception as f:
            print(f)
            cls.__conn.rollback
        finally:
            cls.__close_cursor()
            cls.__close_conn()

    @classmethod
    def __close_cursor(cls):
        if cls.__cursor:
            cls.__cursor.close
            cls.__cursor = None

    @classmethod
    def __close_conn(cls):
        if cls.__conn:
            cls.__conn.close
            cls.__conn = None
